<!-- 大屏自适应容器组件 无需固定宽高 按照 window/screen比 处理， 若屏幕小于一定比列特殊处理-->

<template>
	<!-- 对transform特殊处理，等比例缩放 -->
	<div class="ScaleBox" :style="{
		width: width + 'px',
		height: height + 'px',
		transform: `scale(${scale.w},${scale.h}) translate(-50%, -50%)`,
	}">
		<slot></slot>
	</div>
</template>

<script>
/**
 * 防抖函数
 * @param {T} fn
 * @param {number} delay
 * @return
 */
function debounce(fn, delay) {
	let timer = null;
	return function (...args) {
		timer = setTimeout(
			() => {
				typeof fn === "function" && fn.apply(null, args);
				clearTimeout(timer);
			},
			delay > 0 ? delay : 100
		);
	};
}
export default {
	data() {
		return {
			scale: {
				//缩放比
				w: 1,
				h: 1,
			},
			width: screen.width, //宽度
			height: screen.height, //高度
			reCalc: null, //自适应函数
		};
	},
	mounted() {
		// 初始化时设置自适应函数
		this.reCalc = debounce(() => {
			this.setScale();
		});
		this.setScale();
		this.addListener();
	},
	beforeDestroy() {
		// 页面销毁时移除监听事件
		this.clearListener();
	},
	methods: {
		/**
		 * @description 获取缩放值，并特殊处理
		 */
		getScale() {
			//缩放值 按照 window/screen 处理， 若屏幕小于一定比列特殊处理
			const w = window.innerWidth / this.width;
			const h = window.innerHeight / this.height;
			if (window.innerWidth <= 800 || window.innerHeight <= 600) {
				let scale = w < h ? w : h;
				return [scale, scale];
			}
			return [h, w];
		},

		/**
		 * @description 设置缩放比
		 */
		setScale() {
			// 缩放比
			this.scale.h = this.getScale()[0];
			this.scale.w = this.getScale()[1];
		},

		/**
		 * @description 添加resize监听事件
		 */
		addListener() {
			window.addEventListener("resize", this.reCalc);
		},

		/**
		 * @description 移除resize监听事件
		 */
		clearListener() {
			window.removeEventListener("resize", this.reCalc);
		},
	},
};
</script>

<style scoped lang="scss">
.ScaleBox {
	position: absolute;
	// transform: scale(v-bind('scale.w'), v-bind('scale.h')) translate(-50%, -50%);
	display: flex;
	flex-direction: column;
	transform-origin: top left;
	left: 50%;
	top: 50%;
	// transition: 0.2s;
	z-index: 999;
	// background: rgba(255, 0, 0, 0.3);
}
</style>
